//
//  WBComposeViewController.swift
//  WBWeiBo
//
//  Created by 王斌 on 16/7/19.
//  Copyright © 2016年 王斌. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBComposeViewController: UIViewController {
    
    // MARK:    -懒加载控件
    private lazy var titleLabel: UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 17)
        
        
        label.numberOfLines = 0
        label.textAlignment = .Center
        //  获取用户名
        if let name = WBUserAccountViewModel.shareUserAccount.userAccount?.name {
            
            
            let title = "发微博\n\(name)"
            let attributeStr = NSMutableAttributedString(string: title)
            // 获取名字的范围
            let range = (title as NSString).rangeOfString(name)
            
            attributeStr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(12)], range: range)
            
            label.attributedText = attributeStr
        } else {
            label.text = "发微博"
        }
        
        
        
        label.sizeToFit()
        
        return label
        
    }()
    
    //  右侧按钮(发送按钮)
    private lazy var rightButton: UIButton = {
        
        let button = UIButton()
        //  添加点击事件
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        button.setTitle("发送", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        button.size = CGSize(width: 45, height: 30)
        //  因为button被UIBarButtonItem,这样设置没有作用
        //        button.enabled = false
        return button
        
    }()
    
    //  添加自定义Textview
    private lazy var textView: WBComposeTextView = {
        let view = WBComposeTextView()
        view.delegate = self
        view.placeHolder = "叶的飘零,是风的追求,还是树的不挽留..."
        view.font = UIFont.systemFontOfSize(15)
        //  垂直方向开启弹簧效果
        view.alwaysBounceVertical = true
        return view
        
    }()
    //  toolbar
    private lazy var toolBar: WBComposeToolBar = {
        let view = WBComposeToolBar(frame: CGRectZero)
        return view
        
    }()
    //  配图
    private lazy var pictureView: WBComposePictureView = {
        let view = WBComposePictureView()
        return view
        
    }()
    //  表情键盘
    private lazy var keyBoard: WBEmoticonBoard = {
        let view = WBEmoticonBoard()
        //  设置视图大小
        view.size = CGSize(width: self.textView.width, height: 216)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
    }
    
    private func setupUI() {
        
        //  监听键盘改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //  监听表情按钮的点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedEmoticon:", name: DidSeletedEmotionButtonNotification, object: nil)
        //  监听删除表情按钮的点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedDeleteEmoticon", name: DidSelecteDeleteEmoticonButtonNotification, object: nil)
        
        setupNavUI()
        
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(self.toolBar.snp_top)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(30)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.leading.equalTo(textView).offset(10)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }
        
        //  设置闭包
        toolBar.selectedToolBarButtonClosure = { [weak self] (type: WBcomposeToolBarButtonType) in
            
            switch type {
            case .Picture:
                print("图片")
                self?.didSelectedPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("话题")
            case .Emoticon:
                print("表情")
                self?.didSelectedEmoticon()
            case .Add:
                print("加号")
            }
            
            
        }
        
        pictureView.didSelectedAddClosure = { [weak self] in
            //  打开图片选择器
            self?.didSelectedPicture()
        }
        
        
        
    }
    
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    // MARK:    -- 监听删除表情按钮点击的通知
    @objc private func didSelectedDeleteEmoticon() {
        //  删除内容
        textView.deleteBackward()
        
    }
    
    
    // MARK:    --  监听表情按钮点击的通知
    @objc private func didSelectedEmoticon(noti: NSNotification) {
        
        let emoticon = noti.object as! WBEmoticon
        textView.insertEmoticon(emoticon)
        
    }
    
    // MARK:    --  监听键盘frame改变的事件
    @objc private func keyboardChangeFrame(noti: NSNotification) {
        
        
        //  获取屏幕的frame
        let keyboardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //  获取动画时长
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        //  更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - ScreeHeight)
        }
        
        //  执行动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    
    // MARK: -- 点击事件处理
    @objc private func cancelAction() {
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    //  发送微博
    @objc private func sendAction() {
        
        //        //  根据指定的范围,遍历我们的富文本
        //        //  infoDic - 表示遍历到内容
        //        //  range  - 表示遍历到范围
        //        //  stop   - 是否停止      a.memory = true
        //        var result = ""
        //        textView.attributedText.enumerateAttributesInRange(NSMakeRange(0, textView.attributedText.length), options: []) { (infoDic, range, _) -> Void in
        //
        //
        ////            print(infoDic["NSAttachment"])
        //
        //            if let attachment = infoDic["NSAttachment"] as? CZTextAttachment {
        //                //  有图片
        //
        //                let chs = attachment.emoticon!.chs!
        //                //  拼接表情描述
        //                result += chs
        //
        //            } else {
        //                //  文字
        //                //  获取指定范围内的文字
        //                let text = self.textView.attributedText.attributedSubstringFromRange(range).string
        //                result += text
        //
        //            }
        //
        //        }
        //        print(result)
        
        
        
        //  带图片微博上传接口
        if pictureView.images.count > 0 {
            //  带图片微博上传接口
            upload()
            //            let image = pictureView.images.first!
            //            let accessToken = CZUserAccountViewModel.shareUserAccount.accessToken!
            //            //  获取富文本对应的字符串
            //            let text = textView.emoticonString //textView.text!
            //            SVProgressHUD.show()
            //            CZNetworkTools.sharedToos.upload(accessToken, status: text, image: image, callBack: { (response, error) -> () in
            //                if error != nil {
            //                    print(error)
            //                    SVProgressHUD.showErrorWithStatus("发送失败")
            //                    return
            //                }else {
            //                    //  发送成功
            //                    SVProgressHUD.showSuccessWithStatus("发送成功")
            //                }
            //            })
        } else {
            //  发送文字微博接口
            update()
            //            //  发送文字微博接口
            //            let accessToken = CZUserAccountViewModel.shareUserAccount.accessToken!
            //            //  获取富文本对应的字符串
            //            let text = textView.emoticonString //textView.text!
            //            SVProgressHUD.show()
            //            CZNetworkTools.sharedToos.update(accessToken, status: text) { (response, error) -> () in
            //                if error != nil {
            //                    print(error)
            //                    SVProgressHUD.showErrorWithStatus("发送失败")
            //                    return
            //                }
            //
            //
            //                //  发送成功
            //                SVProgressHUD.showSuccessWithStatus("发送成功")
            //            }
        }
        
        
        
        
    }
    
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //  上传图片微博即可
    private func upload() {
        let image = pictureView.images.first!
        let accessToken = WBUserAccountViewModel.shareUserAccount.accessToken!
        //  获取富文本对应的字符串
        let text = textView.emoticonString //textView.text!
        SVProgressHUD.show()
        WBNetworkTools.sharedTools.upload(accessToken, status: text, image: image, callBack: { (response, error) -> () in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }else {
                //  发送成功
                SVProgressHUD.showSuccessWithStatus("发送成功")
            }
        })
        
    }
    
    //  发送文字微博接口
    private func update() {
        
        //  发送文字微博接口
        let accessToken = WBUserAccountViewModel.shareUserAccount.accessToken!
        //  获取富文本对应的字符串
        let text = textView.emoticonString //textView.text!
        SVProgressHUD.show()
        WBNetworkTools.sharedTools.update(accessToken, status: text) { (response, error) -> () in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            
            
            //  发送成功
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
        
    }
    
    
}
//  处理toolbar按钮点击的逻辑
extension WBComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    //  表情键盘处理
    func didSelectedEmoticon() {
        //  显示表情键盘或者系统键盘
        if textView.inputView == nil {
            //  设置inputView 表情键盘
            
            textView.inputView = keyBoard
            //  设置键盘显示的icon
            toolBar.showEmotionIcon(true)
        } else {
            //  设置成系统键盘
            textView.inputView = nil
            //  设置键盘显示的icon
            toolBar.showEmotionIcon(false)
        }
        
        //  获取第一响应者
        textView.becomeFirstResponder()
        //  重新刷新inputview
        textView.reloadInputViews()
        
    }
    
    
    //  图片处理
    func didSelectedPicture() {
        let imagePictureCtr = UIImagePickerController()
        //  设置代理
        imagePictureCtr.delegate = self
        //  判断是否支持这个来源类型
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            imagePictureCtr.sourceType = .Camera
            print("支持相机")
        } else {
            imagePictureCtr.sourceType = .PhotoLibrary
            print("不支持相机,使用的图库")
        }
        
        //  判断是否支持前置或者后者摄像头
        if UIImagePickerController.isCameraDeviceAvailable(.Front) {
            print("支持前置摄像头")
        } else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            print("支持后置摄像头")
        } else {
            print("前后置摄像头不支持")
        }
        //  允许用户编辑
        //imagePictureCtr.allowsEditing = true
        
        presentViewController(imagePictureCtr, animated: true, completion: nil)
        
        
        
    }
    //  获取选中的图片 , 如果实现了协议就不会自己调用dismissViewControllerAnimated
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //  获取压缩后的图片
        let scaleImage = image.scaleImageWithScaleWidth(200)
        print(scaleImage)
        
        pictureView.addImage(scaleImage)
        
        
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //    /**
    //     根据指定压缩后的宽度,压缩图片
    //
    //     - parameter width: 压缩的宽度
    //     - parameter image: 需要压缩的图片
    //     
    //     - returns:   压缩后的图片
    //     */
    //    private func scaleImageWithScaleWidth(scaleWidth: CGFloat, image: UIImage) -> UIImage {
    //    
    //        //  根据压缩后的宽度计算压缩后的高度
    //        let scaleHeight = scaleWidth / image.size.width * image.size.height
    //        
    //        //  压缩后的大小
    //        let size = CGSize(width: scaleWidth, height: scaleHeight)
    //        //  开启上下文
    //        UIGraphicsBeginImageContext(size)
    //        
    //        //  把图片渲染到指定范围内
    //        image.drawInRect(CGRect(origin: CGPointZero, size: size))
    //        //  获取上下文中压缩后的图片
    //        let scaleImage = UIGraphicsGetImageFromCurrentImageContext()
    //        
    //        //  关闭上下文
    //        UIGraphicsEndImageContext()
    //        
    //        return scaleImage
    //        
    //    }
    
    
    
    
    
    
}


extension WBComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        //  根据文本内容判断发送按钮是否可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
}






